package com.lg.product.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.product.entity.Brand;
import com.lg.product.entity.CategoryBrand;
import com.lg.product.mapper.BrandMapper;
import com.lg.product.service.IBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lg.product.service.ICategoryBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * <p>
 * 品牌表，一个品牌下有多个商品（spu），一对多关系 服务实现类
 * </p>
 *
 * @author song
 * @since 2020-07-22
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

    @Autowired
    private ICategoryBrandService iCategoryBrandService;

    /**
     *  分页查询
     * @param brand
     * @param page
     * @return
     */
    public IPage<Brand> pageInfo(Brand brand,Page page){

        return baseMapper.pageInfo(brand,page);
    }

    /**
     * 品牌 删除
     * @param id
     * @return
     */
    public int deleteBrand(Integer id){
        baseMapper.deleteById(id);
        return 1;
    }

    /**
     * 品牌 添加
     * @param brand
     * @return
     */
    @Override
    public int addBrand(Brand brand) {
         baseMapper.insert(brand);
        System.out.println("=========="+brand.getId());
        String[] split = brand.getZjId().split(",");
        for (String  sp : split){
            CategoryBrand categoryBrand = new CategoryBrand();
            categoryBrand.setBrandId(brand.getId());
            Integer i = Integer.parseInt(sp);
            System.out.println("=****="+i.longValue());
            categoryBrand.setCategoryId(i.longValue());
            //添加中间表
            iCategoryBrandService.save(categoryBrand);
    }
       return 1;
    }

    /**
     * 品牌 回显
     * @param id
     * @return
     */
    public Brand listId(Integer id){

        Brand brand = baseMapper.selectById(id);
        return brand;
    }
    /**
     * 品牌 修改
     * @param brand
     * @return
     */
    @Override
    public int updateBrand(Brand brand) {
        //修改品牌表
         baseMapper.updateById(brand);

        System.out.println("=========="+brand.getId());
        String[] split = brand.getZjId().split(",");
        for (String  sp : split){
            //删除中间表
            iCategoryBrandService.removeById(brand.getId());
            CategoryBrand categoryBrand = new CategoryBrand();
            categoryBrand.setBrandId(brand.getId());
            Integer i = Integer.parseInt(sp);
            categoryBrand.setCategoryId(i.longValue());
            //添加中间表
            iCategoryBrandService.save(categoryBrand);
        }
        return 1;
    }



}
